package com.rice.study.util;

import org.springframework.util.StringUtils;

public class IpUtils {

    /**
     * @author anqun.xu
     * @Description: 将二进制字符串换成ip
     * @params
     * @return
     * @date
     */
    public static String binaryString2Ip(String binaryString){
        if (StringUtils.isEmpty(binaryString)){
            return "未知";
        }

        if ("0".equals(binaryString)){
            return "0.0.0.0";
        }

        if (binaryString.length() != 32){
            return "未知";
        }

        String str1 = binaryString.substring(0, 8);

        String str2 = binaryString.substring(8, 16);

        String str3 = binaryString.substring(16, 24);

        String str4 = binaryString.substring(24, 32);


        String endIp = Integer.parseInt(str1,2) + "." + Integer.parseInt(str2,2) + "." + Integer.parseInt(str3,2) + "." + Integer.parseInt(str4,2);

        return  endIp;
    }

    /**
     * @author anqun.xu
     * @Description:将IP换成Long
     * @params
     * @return
     * @date
     */
    public static Long ip2Long(String ip){
        if (StringUtils.isEmpty(ip)){
            return null;
        }

        String[] ipList = ip.split("\\.");
        if (ipList.length != 4){
            return null;
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < ipList.length; i++) {
            String ipItem = ipList[i];
            String ip2 = Integer.toBinaryString(Integer.parseInt(ipItem));
            for (int f = 0; f < 8 - ip2.length(); f++){
                sb.append("0");
            }
            sb.append(ip2);
        }

        String ipNunStr = sb.toString();

        Long num2Ip = Long.parseLong(ipNunStr, 2);
        return num2Ip;

    }

    public static String long2Ip(Long l){

        String binaryString = Long.toBinaryString(l);
        String endIp = binaryString2Ip(binaryString);
        return endIp;

    }


    public static void main(String[] args){
        String ipStr = "0.0.0.0";
        Long num2Ip = ip2Long(ipStr);
        System.out.println(num2Ip);

        String endIp = long2Ip(num2Ip);

        System.out.println("ip is " + endIp);

    }
}
